﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace MuYue.Config
{
    /// <summary>
    /// 对象性配置
    /// 这个类不能直接创建 只能使用AppConfigManager的GetConfig方法获取
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class AppConfig<T>
    {
        internal AppConfig(AppConfigModel model, T defaultValue, AppConfigManager.AppConfigWriteDelegate updateMethod)
        {
            this.mModel = model;
            if (this.mModel.Value != defaultValue.ToString())
            {
                if (defaultValue is string)
                {
                    defaultValue = (T)(object)this.mModel.Value;
                }
                else
                {
                    try
                    {
                        defaultValue = (T)typeof(T).InvokeMember("Parse", BindingFlags.InvokeMethod, null, null, new[] { this.mModel.Value });
                    }
                    catch (Exception ex) { Console.WriteLine("{0}", ex.Message); }
                }
            }
            this.mValue = defaultValue;
            this.UpdateAppCofingItem += updateMethod;
        }

        #region 私有字段
        private AppConfigModel mModel;
        private T mValue;
        #endregion

        public T Value
        {
            set
            {
                //检查值是否相等
                if (this.mModel.Value != value.ToString())
                {
                    this.mValue = value;
                    this.mModel.Value = value.ToString();
                    if (UpdateAppCofingItem != null)
                        UpdateAppCofingItem(this.mModel);
                    //如果要实现数据绑定的话还需要进行下一层次的封装
                }
            }
            get { return mValue; }
        }

        #region 外接事件
        private AppConfigManager.AppConfigWriteDelegate UpdateAppCofingItem;
        #endregion

    }
}
